<?php
/**
 * Created by PhpStorm.
 * User: zhan
 * Date: 2018/1/2  14:21
 */
namespace app\api\logic;
use app\api\BaseModel;

class Shop extends  BaseModel
{
    /**
     * 商铺列表
     */
    public function index()
    {
        $p=isset($this->requestData['page'])?$this->requestData['page']:'1';
        $size=isset($this->requestData['limit'])?$this->requestData['limit']:'10';
        $lat  =isset($this->requestData['lat'])?trim($this->requestData['lat']): '23.13098';
        $lng =isset($this->requestData['lng'])?trim($this->requestData['lng']):  '113.403873';
        $search=isset($this->requestData['search'])?$this->requestData['search']:'';
        $sort=isset($this->requestData['sort'])?$this->requestData['sort']:'0';
        $cid=isset($this->requestData['cid'])?$this->requestData['cid']:0;

        $condition = 's.is_mention=1';
        $condition .=' and s.status=1 and  s.isopen=1';

        if($cid){
            $condition.=' and cid="'.$cid.'"';
        }
        if($search) {
            $condition .= ' and shopname like "%' . $search . '%"';
        }

        $field = "ROUND(6378.138 * 2 * ASIN(SQRT(POW(SIN(({$lat} * PI() / 180 - s.lat * PI() / 180) / 2
					),2) + COS({$lat} * PI() / 180) * COS(s.lat * PI() / 180) * POW(SIN(({$lng} * PI() / 180 - s.lng * PI() / 180) / 2
					),2))) * 1000) AS juli";

        $list = db()->query("select s_view.* from (select s.id,s.shopname,s.street as streets,s.headimage,s.lat,s.lng,c.name as catetoryname,s.discount,s.issend,s.commission,s.province,s.city,s.county,s.street,s.address,{$field} from jdw_shop as s inner join jdw_category_shop as c on c.id = s.cid where {$condition}) as s_view where s_view.juli < 50000 order by s_view.juli asc");

        $db_order=db("order");
        $data['list']=array();
        if($list) {
            foreach ($list as $k => $val) {
                $radLat1 = deg2rad($lat);
                $radLat2 = deg2rad($val['lat']);
                $a = $radLat1 - $radLat2;
                $b = deg2rad($lng) - deg2rad($val['lng']);
                $s = 2 * asin(sqrt(pow(sin($a / 2), 2) + cos($radLat1) * cos($radLat2) * pow(sin($b / 2), 2)));
                $meter = $s * 6378137.0;
                $distant[] = $meter;
                if ($meter > 1000) {
                    $meter = number_format($meter / 1000, 2) . 'km';
                } else {
                    $meter = number_format($meter, 2) . 'm';
                }
                $list[$k]['distant'] = $meter;
                if ($val['headimage']) {
                    $list[$k]['headimage'] = IMG_PATH . $val['headimage'];
                }
                $or['o.shop_id'] = $val['id'];
                $or['o.status'] = ['in',['1','2','3','-2']];
                $or['o.pay_time'] = array('between', [time() - 30 * 24 * 60 * 60, time()]);
                $order_num = $db_order->alias('o')->join('order_goods og','og.order_id=o.id')->where($or)->sum('og.goods_num');
                $list[$k]['ordernum'] = $order_num;
                if ($val['discount']) {
                    $list[$k]['discount'] = unserialize($val['discount']);
                }
                $ids[]=$val['id'];
                $num[]= $list[$k]['ordernum'];
                if(empty($val['commission'])){
                    $member_config_value = db('config')->where(['id'=>'6'])->value('value');
                    $list[$k]['commission'] = $member_config_value;
                }
            }

            if ($sort == 0) {
                //array_multisort($ids, SORT_ASC, $list);
            } elseif ($sort == 1) {
                //array_multisort($num, SORT_DESC, $list);
            } elseif ($sort == 2) {
                //array_multisort($distant, SORT_ASC, $list);
            }
            $shop = array_chunk($list, $size);
            $count = count($shop);
            if ($p > $count || $p < 1) return array("message" => '页码有误');
            $data['list'] = $shop[$p - 1];
            $data['count'] = count($list);;
        }
        $data['page_num']=$p;
        $data['page_limit']=$size;
        return $data;
    }

    /**
     * 商铺详情
     */
    public function detail()
    {
        (new \app\api\validate\Shop())->detail();

        $condition['s.id']=$this->requestData['id'];
        $shop=db('shop')
            ->alias('s')
            ->field("s.id,s.shopname,s.street,s.headimage,s.lat,s.lng,c.name as catetoryname,s.discount,s.notice,s.isbook,s.issend,s.send_fee,s.des,s.full_distribution,s.commission,s.open_time,s.delivery_time,s.mobile,s.province,s.city,s.county,s.street,s.address,s.mobile")
            ->join("category_shop c","c.id=s.cid")
            ->where($condition)
            ->find();
        if($shop['headimage']) {
            $shop['headimage'] = IMG_PATH . $shop['headimage'];
        }
        if($shop['discount']) {
            $shop['discount'] = unserialize($shop['discount']);
        }
        if(empty($shop['commission'])){
            $member_config = db('config')->where(['id'=>'6'])->value('value');
            $shop['commission'] = $member_config;
        }
        if(!empty($shop['open_time'])){
            $shop['open_time'] = unserialize($shop['open_time']);
        }
        if(!empty($shop['delivery_time'])){
            $shop['delivery_time'] = unserialize($shop['delivery_time']);
        }
        $cate['shop_id']=$shop['id'];
        $cate['status']=1;
        $category=db("category_goods")
            ->where($cate)
            ->order("sort desc,id asc")
            ->select();
        $db_order = db("order");
        $db_option = db("goods_option");
        $db_param = db("goods_param");
        foreach($category as &$e) {
            $where['cid']=$e['id'];
            $where['status'] = 1;
            $where['shop_id'] = $shop['id'];
            $goods = db("goods")->field("id,name,des,image,label,price,oldprice,stock,shop_id")->where($where)->select();

            foreach ($goods as &$v) {
                if ($v['image']) {
                    $v['image'] = IMG_PATH . $v['image'];
                }
                $or['o.shop_id'] = $v['shop_id'];
                $or['o.status'] = ['in',['1','2','3','-2']];
                $or['o.pay_time'] = array('between', [time() - 30 * 24 * 60 * 60, time()]);
                $or['og.goods_id'] = $v['id'];
                $order_num = $db_order->alias('o')->join('order_goods og','og.order_id=o.id')->where($or)->sum('og.goods_num');
                $v['ordernum'] = $order_num;
                $v['option'] = $db_option->where("goodsid=" . $v['id'])->select();
                if($v['option']){
                    $v['price']=  $v['option'][0]['price'];
                }
                $param = $db_param->field("title,param")->where("goodsid=" . $v['id'])->select();
                foreach ($param as &$d) {
                    $d['param'] = unserialize($d['param']);
                }
                $v['params'] = $param;
            }
            $e['goods']=$goods;
        }
        $coll['uid']=$this->user['id'];
        $coll['shop_id']=$this->requestData['id'];
        if(db("collect")->where($coll)->find()){
            $data['iscollect']=1;
        }else{
            $data['iscollect']=0;
        }
        $data['shop']=$shop;
        $data['category']=$category;
        $data['comment_num']=db("comment")->where("shop_id=".$this->requestData['id']." and status=0")->count();
        //查询出打印机编号
        $printer_id = db('printer')->where(['shop_id'=>$condition['s.id']])->field('printer_id')->find();
        if(!empty($printer_id)){
            $data['printer_id'] = $printer_id['printer_id'];
        }else{
            $data['printer_id'] = '';
        }

        return $data;
    }
    /**
     *店铺分类
     */
    public function category()
    {
        $p=isset($this->requestData['page'])?$this->requestData['page']:'1';
        $size=isset($this->requestData['limit'])?$this->requestData['limit']:'10';
        $category_result = db('category_shop')->where("status=1")->order("sort desc")->select();
        $where['cid'] = $category_result[0]['id'];
        $shop_result = db('shop')->where($where)->page($p,$size)->field('shopname')->select();
        $data['category'] = $category_result;
        return $data;
    }
    /**
     *店铺分类详情
     */
    public function category_detail()
    {
        $cid = $this->requestData['cid'];
        $where['cid'] = $cid;
        $shop_result = db('shop')->where($where)->field('shopname')->select();
        $data['shoplist'] = $shop_result;
        return $data;
    }
    /**
     * 商铺评论
     */
    public function comment()
    {
        (new \app\api\validate\Shop())->detail();

        $shop_id=$this->requestData['id'];
        $p=isset($this->requestData['page'])?$this->requestData['page']:'1';
        $size=isset($this->requestData['limit'])?$this->requestData['limit']:'10';
        $comment= db("comment")->alias("c")
            ->field("m.nickname,m.headimage,c.*")
            ->join("member m","m.id=c.uid")
            ->where("c.shop_id=".$shop_id." and c.status=0")
            ->order("id desc")
            ->page($p,$size)
            ->select();
        $count= db("comment")->alias("c")
            ->field("m.nickname,m.headimage,c.*")
            ->join("member m","m.id=c.uid")
            ->where("c.shop_id=".$shop_id." and c.status=0")
            ->count();
        foreach($comment as &$v){
            $v['create_time']=date("Y-m-d",$v['create_time']);
            if($v['images']){
                $images=unserialize($v['images']);
                $img=[];
                foreach($images as &$d){
                    $img[]=ORDER_COMMENT_IMG_PATH.$d;
                }
                $v['images']=$img;
            }
        }
        $data['list'] = $comment;
        $data['count'] = $count;;
        $data['page_num']=$p;
        $data['page_limit']=$size;
        return $data;
    }
    /**
     * 商铺信息
     */
    public function info()
    {
        (new \app\api\validate\Shop())->detail();

        $shop_id=$this->requestData['id'];
        $db_order=db('order');
        $shop=db("shop")->alias("s")
            ->field("headimage,shopname,province,city,county,street,address,discount,tell,images,open_time,c.name,notice,s.des")
            ->join("category_shop c","c.id=s.cid")
            ->where("s.id='$shop_id'")->find();
        $or['o.shop_id'] = $shop_id;
        $or['o.status'] = ['in',['1','2','3','-2']];
        $or['o.pay_time'] = array('between', [time() - 30 * 24 * 60 * 60, time()]);
        $order_num = $db_order->alias('o')->join('order_goods og','og.order_id=o.id')->where($or)->sum('og.goods_num');
        $shop['ordernum'] = $order_num;

        foreach ($shop as $key => &$value) {
            if(empty($value)){
                $value = '';
            }
        }

        if (isset($shop['discount'])) {
            $shop['discount'] = unserialize($shop['discount']);
        }else{
            $shop['discount'] = '';
        }
        if (isset($shop['headimage'])) {
            $shop['headimage'] = IMG_PATH.$shop['headimage'];
        }else{
            $shop['headimage'] = '';
        }
        if(isset($shop['images'])){
            $images=unserialize($shop['images']);
            $img=[];
            if($images){
                foreach($images as &$d){
                    $img[]=IMG_PATH.$d;
                }
            }
            $shop['images']=$img;
        }else{
            $shop['images']=[];
        }
        if (isset($shop['open_time'])) {
            $shop['open_time'] = unserialize($shop['open_time']);
        }else{
            $shop['open_time'] = '';
        }
        return $shop;
    }
    /**
     * 商铺资质
     */
    public function qualifications()
    {
        (new \app\api\validate\Shop())->detail();
        $shop_id=$this->requestData['id'];
        $shop=db("shop")
            ->field("shopname,province,city,county,street,address,realname,licensekey,scope,food_term,license,foodlicense")
            ->where("id='$shop_id'")->find();

        foreach ($shop as $key => &$value) {
            if(empty($value)){
                $value='';
            }
        }

        if(isset($shop['license'])){
            $shop['license']=IMG_PATH_LICENSE.$shop['license'];
        }else{
            $shop['license']='';
        }
        if(isset($shop['foodlicense'])){
            $shop['foodlicense']=IMG_PATH_LICENSE.$shop['foodlicense'];
        }else{
            $shop['foodlicense']='';
        }
        return $shop;
    }

    /**
     * 收藏店铺与取消
     */
    public function collect()
    {
        (new \app\api\validate\Shop())->detail();
        $where['shop_id']=$this->requestData['id'];
        $es['id']=$this->requestData['id'];
        $es['status']=1;
        $shop=db("shop")->where($es)->find();
        if(!$shop) return array("message"=>'店铺不存在');
        $where['uid']=$this->user['id'];
        $collect=db("collect")->where($where)->find();
        if($collect){
            $res=db("collect")->where($where)->delete();
            $data['status']=0;
        }else{
            $res=db("collect")->insert($where);
            $data['status']=1;
        }
        if(!$res) return array("message"=>'操作失败');
        return $data;
    }

    /**
     * 店铺流水
     */
    public function capital_flow()
    {
        $shop_id = $this->requestData['shop_id'];
        $page = isset($this->requestData['page'])?$this->requestData['page']:1;

        $order_stream = db('order_stream')->alias('os')->join('order o','o.id=os.order_id')->where(['os.shop_id'=>$shop_id])->field('os.*,o.order_sn')->page($page,'10')->select();

        return $order_stream;
    }
}